package com.gjzt.business.bid.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Service;
import com.eastdigit.system.model.SqlBuilder;
import com.eastdigit.system.service.BaseService;
import com.eastdigit.util.StringUtil;
import com.gjzt.business.utils.Constant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 根据竞价单截止时间更改竞价单信息
 * 
 * 把竞价单的截止时间（精確到小時）与当前时间做比对， 如果当前时间大于等于截止时间， 则更改竞价单状态为“竞价结束”，同时价高者竞价成功。
 * 
 * @author zwm
 *
 */
@Service
public class BidEndService extends BaseService {

	public void letBidEnd() throws ParseException {
		SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH");
		// 查询所有竞价中的竞价单
		SqlBuilder getAllPublishedBidSlq = new SqlBuilder(
				"select  *  from AD_BIDDING  ab  where ab.`STATUS`=" + Constant.BIDSTATUS_IN);
		JSONArray bidArray = this.query(getAllPublishedBidSlq);
		for (int i = 0; i < bidArray.size(); i++) {
			JSONObject bid = bidArray.getJSONObject(i);
			String bidTitle = bid.getString("bidTitle");
			String limitTimeStr = bid.getString("limitTime");
			String bidId = bid.getString("bidId");
			Date limitTime = new Date();
			if(StringUtil.isNotEmpty(limitTimeStr)){
				 limitTime = adf.parse(limitTimeStr);
			}else {
				System.out.println("竞价单: "+bidTitle+" 没有截止时间,不做任何处理");
				continue;
			}
			if (!limitTime.after(new Date())) {// 当前时间大于等于截止时间
				// 查询所有的竞价记录
				SqlBuilder getBidRecodeSlq = new SqlBuilder("select * from AD_BIDDING_RECORD  abr where abr.BID_ID='"
						+ bidId + "' ORDER BY abr.BID_PRICE desc");
				JSONArray bidRecodeArray = this.query(getBidRecodeSlq);
				if (bidRecodeArray != null && bidRecodeArray.size() > 0) {// 更改状态、中标信息
					JSONObject json = bidRecodeArray.getJSONObject(0);// 取最高出价者
					String customerId = json.getString("customerId");
					String bidPrice = json.getString("bidPrice");
					this.jdbcTemplate.update("update AD_BIDDING  ab set ab.`STATUS`=" + Constant.BID_STATUS_FINISH
							+ ",ab.CUSTOMER_ID=" + customerId + ",ab.WINNING_PRICE=" + bidPrice + " where ab.BID_ID='"
							+ bidId + "'");
				} else {// 没有竞价记录,只更改竞价单状态
					this.jdbcTemplate.update("update AD_BIDDING  ab set ab.`STATUS`=" + Constant.BID_STATUS_FINISH
							+ " where ab.BID_ID='" + bidId + "'");
				}
			}
		}
	}
	
}